<script lang="tsx" setup>
import { computed, reactive, ref, watch } from 'vue';
import { type FormRules } from 'naive-ui';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import type { DictDataVo, DictTypeVo } from '@/service/types/developer';
import { addDictType, editDictType, getDictType } from '@/service/api/developer/dictType';
type Model = Pick<DictTypeVo, 'dictId' | 'dictName' | 'dictType' | 'remark'>;
interface Props {
  operateType: NaiveUI.TableOperateType;
  currentDictTypeId?: string | number | null | unknown;
}
defineOptions({
  name: 'DictTypeForm'
});
const loading = ref(false);
interface Emits {
  (e: 'submitted'): void;
}
const show = ref<boolean>(false);
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();
const rules: FormRules = {
  dictName: createRequiredRule('字典名称不能为空'),
  dictType: createRequiredRule('字典类型不能为空')
};

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增字典类型',
    edit: '修改字典类型'
  };
  return titles[props.operateType];
});
const visible = defineModel<boolean>('visible', {
  default: false
});
const currentModelData = ref<DictDataVo>();
const model: Model = reactive(createDefaultModel());
function createDefaultModel(): Model {
  return {
    dictName: '',
    dictType: '',
    dictId: '',
    remark: ''
  };
}
const getDictTypeById = async (id: number) => {
  show.value = true;
  const { error, data } = await getDictType(id);
  if (!error) {
    // @ts-expect-error 忽略request data
    currentModelData.value = data?.data;
  }
  show.value = false;
};

async function handleInitModel() {
  Object.assign(model, createDefaultModel());
  if (props.operateType === 'edit' && props.currentDictTypeId) {
    await getDictTypeById(props.currentDictTypeId as number);
    Object.assign(model, currentModelData.value);
  }
}
watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});

const closeModal = () => {
  visible.value = false;
};
const submitAddDictType = async (params: DictTypeVo) => {
  const { error, data } = await addDictType(params);
  loading.value = false;
  if (!error) {
    (window as any).$message?.success(data?.msg);
    closeModal();
    emit('submitted');
  }
};
const submitEditDictType = async (params: DictTypeVo) => {
  const { error, data } = await editDictType(params);
  loading.value = false;
  if (!error) {
    (window as any).$message?.success(data?.msg);
    closeModal();
    emit('submitted');
  }
};
async function handleSubmit() {
  await validate();
  loading.value = true;
  const { ...params } = model;
  if (!props.currentDictTypeId) {
    await submitAddDictType(params as DictTypeVo);
  } else {
    await submitEditDictType({ ...params, dictId: props.currentDictTypeId } as DictTypeVo);
  }
}
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" class="w-540px">
    <NSpin :show="show">
      <NForm ref="formRef" :model="model" :rules="rules">
        <NGrid x-gap="12" responsive="screen" item-responsive>
          <NFormItemGi span="24 s:24 m:24" label="字典名称" path="dictName">
            <NInput v-model:value="model.dictName" placeholder="请输入字典名称" />
          </NFormItemGi>
          <NFormItemGi span="24 s:24 m:24" label="字典类型" path="dictType">
            <NInput v-model:value="model.dictType" placeholder="请输入字典类型" />
          </NFormItemGi>
          <NFormItemGi span="24 s:24 m:24" label="备注" path="remark">
            <NInput v-model:value="model.remark" type="textarea" placeholder="请输入备注" />
          </NFormItemGi>
        </NGrid>
      </NForm>
    </NSpin>

    <template #footer>
      <NSpace justify="end">
        <NButton @click="closeModal">取消</NButton>
        <NButton type="primary" :loading="loading" @click="handleSubmit">提交</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style lang="scss" scoped></style>
